package com.hunttown.mes.manage.service;

import com.hunttown.mes.common.keys.KeyConstants;
import com.hunttown.mes.common.cache.Cache;
import com.hunttown.mes.common.utils.ChineseToPinyinUtils;
import com.hunttown.mes.common.utils.FastJsonUtils;
import com.hunttown.mes.common.utils.FormatUtils;
import com.hunttown.mes.common.utils.StringUtils;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.query.AnalysisManageDTOQuery;
import com.hunttown.mes.rpc.api.AnalysisManageRpcService;
import com.hunttown.common.domain.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * created by hunttown on 2018-10-26 15:04:44
 */
@Service
public class AnalysisManageManageService {

    private final static Logger logger = LoggerFactory.getLogger(AnalysisManageManageService.class);

    private final AnalysisManageRpcService rpcService;
    private final AnalysisManageRightRoleManageService roleService;
    private final AHelpManageService helpService;
    private final Cache jedisCache;

    @Autowired
    public AnalysisManageManageService(AnalysisManageRpcService rpcService, AnalysisManageRightRoleManageService roleService, AHelpManageService helpService, Cache jedisCache) {
        this.rpcService = rpcService;
        this.roleService = roleService;
        this.helpService = helpService;
        this.jedisCache = jedisCache;
    }

    // 新增
    public AnalysisManageDTO insert(AnalysisManageDTO objDTO) {
        return rpcService.insert(objDTO);
    }

    // 通过ID修改
    public Boolean updateInfoById(AnalysisManageDTO objDTO) {
        Boolean isNext = rpcService.updateInfoById(objDTO);
        if (isNext) {
            // 刷新用户缓存
            refreshAdminCacheAll(objDTO.getId());
        }
        return isNext;
    }

    // 通过Query修改
    public Boolean updateInfoByQuery(AnalysisManageDTOQuery objDTOQuery) {
        Boolean isNext = rpcService.updateInfoByQuery(objDTOQuery);

        //单个更新
        if (isNext && objDTOQuery.getW_id() != null) {
            refreshAdminCacheAll(objDTOQuery.getW_id());
        }

        //批量更新
        if (isNext && objDTOQuery.getIds() != null) {
            // 刷新用户缓存
            List<Integer> list = new ArrayList<>();
            try {
                list = (List<Integer>) objDTOQuery.getIds();
            } catch (Exception e) {
                e.printStackTrace();
            }
            refreshAdminCacheByIdList(list);
        }

        return isNext;
    }

    // 通过ID删除
    public Boolean delete(Integer id) {
        Boolean isNext = rpcService.deleteById(id);
        if (isNext) {
            // 刷新用户缓存
            refreshAdminCacheAll(id);
        }
        return isNext;
    }

    // 批量删除
    public Boolean deleteForBatch(String clearIds) {

        //处理 “,5,6,7,” 为List
        List<Integer> idList = FormatUtils.commaToList_Integer(clearIds);

        if (idList.size() == 0) {
            return false;
        }

        AnalysisManageDTOQuery query = new AnalysisManageDTOQuery();
        query.setDeleteFlag(1);
        query.setIds(idList);

        Boolean isNext = rpcService.updateInfoByQuery(query);
        if (isNext) {
            // 刷新用户缓存
            refreshAdminCacheByIdList(idList);
        }

        return isNext;
    }

    //region 获取数据

    // 通过ID获取
    public AnalysisManageDTO getById(Integer id) {
        if (id == null || id <= 0) {
            return null;
        }
        return rpcService.selectById(id);
    }

    // 通过Query获取
    public AnalysisManageDTO getByQuery(AnalysisManageDTOQuery objDTOQuery) {
        return rpcService.selectObjByQuery(objDTOQuery);
    }

    // 获取分页列表
    public Page<AnalysisManageDTO> getForPage(AnalysisManageDTOQuery objDTOQuery) {
        return rpcService.getListForPage(objDTOQuery);
    }

    // 获取数量
    public Long getCount(AnalysisManageDTOQuery dtoQuery) {
        return rpcService.countByQuery(dtoQuery);
    }

    // 改变某条记录的使用状态
    public Boolean changeState(Integer id, Integer state) {
        AnalysisManageDTO obj = new AnalysisManageDTO();
        obj.setStopFlag(state);
        obj.setId(id);
        Boolean isNext = rpcService.updateInfoById(obj);

        if (isNext) {
            refreshAdminCacheAll(id);
        }

        return isNext;
    }

    // 从缓存中获取NickName
    public String getNickNameFromCache(Integer id) {
        AnalysisManageDTO manageDTO = getFromCacheId(id);
        return manageDTO == null ? "--" : manageDTO.getNickName();
    }

    public AnalysisManageDTO getByAdminName(String adminName) {
        if (StringUtils.isBlank(adminName)) {
            return null;
        }

        AnalysisManageDTOQuery query = new AnalysisManageDTOQuery();
        query.setAdminName(adminName);

        return getByQuery(query);
    }

    public AnalysisManageDTO getByNickName(String nickName) {
        if (StringUtils.isBlank(nickName)) {
            return null;
        }

        AnalysisManageDTOQuery query = new AnalysisManageDTOQuery();
        query.setNickName(nickName);

        return getByQuery(query);
    }

    public AnalysisManageDTO getByMobile(String mobile) {
        if (StringUtils.isBlank(mobile)) {
            return null;
        }

        AnalysisManageDTOQuery query = new AnalysisManageDTOQuery();
        query.setMobile(mobile);
        query.setDeleteFlag(0);

        return getByQuery(query);
    }

    /**
     * 仅供登录使用，不考虑企业ID
     *
     * @param mobile 手机号
     * @return 用户对象
     */
    public AnalysisManageDTO getByMobileForLogin(String mobile) {
        return rpcService.selectByMobileForLogin(mobile);
    }
    //endregion

    //region 从缓存中获取数据

    /**
     * 通过ID，从缓存中获取
     *
     * @param id 用户ID
     * @return obj
     */
    public AnalysisManageDTO getFromCacheId(Integer id) {
        if (id == null || id <= 0) {
            return null;
        }

        AnalysisManageDTO obj = jedisCache.oget(KeyConstants.ADMIN_INFO_CACHE_KEY_ID + id, AnalysisManageDTO.class);
        if (obj == null) {
            obj = getById(id);
            if (obj != null) {
                jedisCache.oset(KeyConstants.ADMIN_INFO_CACHE_KEY_ID + id, obj);
            }
        }

        return obj;
    }

    /**
     * 先从缓存中获取数据，如果用户缓存为空，从数据库中获取，并将获取的数据添加到缓存。
     *
     * @param adminName 用户pin
     * @return 用户对象
     */
    public AnalysisManageDTO getFromCachePin(String adminName) {
        if (StringUtils.isBlank(adminName)) {
            return null;
        }

        //不同企业可能有相同的用户，所以KEY可能相同
        String key = adminName + "_" + helpService.getEnterpriseId();

        AnalysisManageDTO obj = jedisCache.oget(KeyConstants.ADMIN_INFO_CACHE_KEY_PIN + key, AnalysisManageDTO.class);
        if (obj == null) {
            obj = getByAdminName(adminName);
            if (obj != null)
                jedisCache.oset(KeyConstants.ADMIN_INFO_CACHE_KEY_PIN + key, obj);
        }

        return obj;
    }

    public AnalysisManageDTO getFromCacheNickname(String nickName) {
        if (StringUtils.isBlank(nickName)) {
            return null;
        }

        String key = ChineseToPinyinUtils.ToPinyin(nickName);

        //不同企业可能有相同的用户，所以KEY可能相同
        key += "_" + helpService.getEnterpriseId();

        AnalysisManageDTO obj = jedisCache.oget(KeyConstants.ADMIN_INFO_CACHE_KEY_NICKNAME + key, AnalysisManageDTO.class);
        if (obj == null) {
            obj = getByNickName(nickName);
            if (obj != null) {
                jedisCache.oset(KeyConstants.ADMIN_INFO_CACHE_KEY_NICKNAME + key, obj);
            }
        }

        return obj;
    }

    public AnalysisManageDTO getFromCacheMobile(String mobile) {
        if (StringUtils.isBlank(mobile)) {
            return null;
        }

        //不同企业可能有相同的用户，所以KEY可能相同
        String key = mobile + "_" + helpService.getEnterpriseId();

        AnalysisManageDTO obj = jedisCache.oget(KeyConstants.ADMIN_INFO_CACHE_KEY_MOBILE + key, AnalysisManageDTO.class);
        if (obj == null) {
            obj = getByMobile(mobile);
            if (obj != null) {
                jedisCache.oset(KeyConstants.ADMIN_INFO_CACHE_KEY_MOBILE + key, obj);
            }
        }

        return obj;
    }
    //endregion

    //region 刷新用户缓存

    private void refreshAdminCacheAll(Integer id) {
        if (id == null || id <= 0) {
            return;
        }

        AnalysisManageDTO obj = getById(id);
        if (obj != null) {
            jedisCache.delete(KeyConstants.ADMIN_INFO_CACHE_KEY_ID + id);
            jedisCache.delete(KeyConstants.ADMIN_INFO_CACHE_KEY_PIN + obj.getAdminName() + "_" + obj.getEntId());
            jedisCache.delete(KeyConstants.ADMIN_INFO_CACHE_KEY_NICKNAME + ChineseToPinyinUtils.ToPinyin(obj.getNickName()) + "_" + obj.getEntId());
            jedisCache.delete(KeyConstants.ADMIN_INFO_CACHE_KEY_MOBILE + obj.getMobile() + "_" + obj.getEntId());
        }
    }

    /**
     * 通过用户pin刷新用户缓存
     *
     * @param adminName 用户pin
     */
    public void refreshAdminCache(String adminName) {
        if (StringUtils.isBlank(adminName)) {
            return;
        }

        AnalysisManageDTO obj = getByAdminName(adminName);
        if (obj != null) {
            refreshAdminCacheAll(obj.getId());
        }
    }

    /**
     * 通过用户id刷用户缓存(批量)
     *
     * @param idList id
     */
    private void refreshAdminCacheByIdList(List<Integer> idList) {
        if (idList == null || idList.size() == 0) {
            return;
        }

        for (Integer id : idList) {
            refreshAdminCacheAll(id);
        }
    }
    //endregion

    //region 获取权限菜单

    /**
     * 根据admin_name获取权限菜单ID列表
     *
     * @param adminName 用户pin
     * @return list
     */
    public List<Integer> getMenuIdListByAdminName(String adminName) {
        if (StringUtils.isBlank(adminName)) {
            return null;
        }

        //最终结果
        List<Integer> resultList = new ArrayList<>();

        //根据erp 取出角色id 集合
        List<Integer> roleList = getRoleIdListByAdminName(adminName);
        List<Integer> menuList = new ArrayList<>();

        if (roleList != null && roleList.size() > 0) {
            for (Integer roleId : roleList) {
                //根据角色id 取出权限id 集合
                menuList = roleService.getMenuIdListByRoleId(roleId);

                if (menuList != null && menuList.size() > 0) {
                    for (Integer menuId : menuList) {
                        if (!resultList.contains(menuId)) {
                            resultList.add(menuId);
                        }
                    }
                }
            }
        }

        return resultList;
    }

    /**
     * 根据admin_name获取角色ID列表
     *
     * @param adminName 用户pin
     * @return list
     */
    private List<Integer> getRoleIdListByAdminName(String adminName) {
        List<Integer> list = new ArrayList<>();

        if (StringUtils.isBlank(adminName)) {
            return list;
        }

        AnalysisManageDTO obj = getFromCachePin(adminName);
        if (obj == null) {
            return list;
        }

        return roleService.getRoleIdListByManageId(obj.getId());
    }

    /**
     * 获取角色名称
     *
     * @param list list
     * @return page
     */
    public Page<AnalysisManageDTO> getPageRoleName(Page<AnalysisManageDTO> list) {
        if (list.getItems() == null || list.getItems().size() == 0) {
            return list;
        }

        String roleName = "";

        for (AnalysisManageDTO item : list.getItems()) {
            //根据manageId 取出用户对应的角色Id
            List<Integer> roleIdList = roleService.getRoleIdListByManageId(item.getId());

            //根据角色Id, 取出角色名称
            if (roleIdList != null && roleIdList.size() > 0) {
                for (Integer roleId : roleIdList) {
                    roleName = roleService.getRoleNameById(roleId);
                    //item.setRoles(goToRoleUrl(item.getRoles(), roleId, 0) + " " + goToRoleUrl(roleName, roleId, 0));

                    if (item.getRoles() == null || Objects.equals(item.getRoles(), "")) {
                        item.setRoles(goToRoleUrl(roleName, roleId, 0));
                    } else {
                        item.setRoles(goToRoleUrl(item.getRoles(), roleId, 0) + " " + goToRoleUrl(roleName, roleId, 0));
                    }
                }
            }
        }

        return list;
    }

    private String goToRoleUrl(String roleName, Integer id, Integer parentId) {
        return "<a href=\"javascript:void(0)\" onclick=\"goToEditRole(" + id + ", " + parentId + ")\"><span class=\"label label-table label-danger dis\">" + roleName + "</span></a>";
    }

    //获取用户角色，返回List
    public List<String> getAdminRoles(Integer adminId) {
        List<Integer> roleIdList = roleService.getRoleIdListByManageId(adminId);

        List<String> resRole = new ArrayList<>();

        //根据角色Id, 取出角色名称
        if (roleIdList != null) {
            for (Integer roleId : roleIdList) {
                resRole.add(roleService.getRoleNameById(roleId));
            }
        }

        return resRole;
    }

    // 权限判断
    public Boolean activeUser(String pin, Integer appUserId) {
        AnalysisManageDTO activeObj = getFromCachePin(pin);
        return activeObj.getIsSuper() == 1 || Objects.equals(activeObj.getId(), appUserId);
    }

    //endregion

    //region 模糊搜索管理员
    public List<Map<String, String>> getSimilarManage(String similar) {
        return rpcService.selectSimilarManage(similar);
    }
    //endregion

    //region 获取用户权限菜单代码集合

    /**
     * 获取用户权限菜单代码集合
     * 首先从缓存中获取，如果缓存中不存在，再从数据库获取
     *
     * @param adminId 管理员ID
     * @return list
     */
    private Map<String, String> selectManagerRoleMenu(Integer adminId) {

        Map<String, String> map = new HashMap<>();

        if (adminId == null || adminId <= 0) {
            return map;
        }

        String json = jedisCache.hget(KeyConstants.MENU_ROLE_ADMIN_CACHE_HSET, adminId.toString());

        if (StringUtils.isNotBlank(json)) {
            map = FastJsonUtils.fromJSON(json, Map.class);
        }

        if (map == null || map.size() == 0) {
            map = rpcService.selectManagerRoleMenu(adminId);
            json = FastJsonUtils.toJSONString(map);
            jedisCache.hset(KeyConstants.MENU_ROLE_ADMIN_CACHE_HSET, adminId.toString(), json);
        }

        return map;
    }

    //删除【用户权限菜单】缓存
    public void deleteManagerRoleMenuCache() {
        jedisCache.delete(KeyConstants.MENU_ROLE_ADMIN_CACHE_HSET);
    }

    //更新【用户权限菜单】缓存
    public void updateManagerRoleMenuCache(Integer adminId) {
        Map<String, String> map = rpcService.selectManagerRoleMenu(adminId);
        if (map != null) {
            String json = FastJsonUtils.toJSONString(map);
            jedisCache.hset(KeyConstants.MENU_ROLE_ADMIN_CACHE_HSET, adminId.toString(), json);
        }
    }

    //endregion

    //region 获取用户按钮权限

    /**
     * 获取用户按钮权限
     *
     * @param keys 菜单
     * @param pin  用户PIN
     * @return map
     */
    public Map<String, Boolean> GetBtnPermission(String[] keys, String pin) {
        AnalysisManageDTO obj = getFromCachePin(pin);
        return GetBtnPermission(keys, obj.getId());
    }

    /**
     * 获取用户按钮权限
     *
     * @param keys    菜单
     * @param adminId 用户ID
     * @return map
     */
    private Map<String, Boolean> GetBtnPermission(String[] keys, int adminId) {
        Map<String, Boolean> map = new HashMap<>();

        //如果是管理员，则所有的权限都为true
        AnalysisManageDTO dto = getFromCacheId(adminId);
        if (dto != null && dto.getIsSuper() == 1 && dto.getCustomizeMenu() == 0) {
            for (String item : keys) {
                map.put(item, true);
            }
            return map;
        }

        //普通用户
        Map<String, String> manageMenu = selectManagerRoleMenu(adminId);

        for (String item : keys) {
            if (manageMenu.get(item) != null) {
                map.put(item, true);
            } else {
                map.put(item, false);
            }
        }

        return map;
    }
    //endregion
}